const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const getEntryFile = require('../../../lib/getEntryFile')
const builtInConfig = require('../../../pack.config')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
let externalConfig = {}
let filterEntry = null
if (fs.existsSync(path.resolve(process.cwd(), 'pack.config.js'))) {
  externalConfig = require(path.resolve(process.cwd(), 'pack.config.js'))
  filterEntry = externalConfig.filterEntry
}
let injectEnv = builtInConfig.injectEnv
let injectHtml = builtInConfig.injectHtml
let webEntry = builtInConfig.webEntry;
if (externalConfig.injectEnv) {
  injectEnv = [...injectEnv, ...externalConfig.injectEnv]
}
if (externalConfig.injectHtml) {
  injectHtml = [...injectHtml, ...externalConfig.injectHtml]
}
if (externalConfig.webEntry) {
  webEntry = [...webEntry, ...externalConfig.webEntry]
}
// const before = require('../test')
// const { getPageEntry } = require('./utils');
// const publicPath = process.env.publicPath || '' //process.env.NODE_ENV==='department' ? `` : '/static';
const dirname = process.cwd();
let entry = getEntryFile();


const dealEntry = (entrys) => {

  const entryArray = Object.keys(entrys).map(key => {
    const extname = path.extname(webEntry[key])
    const name = path.basename(webEntry[key])
    const jsEntryKey = name.replace(extname, '');
    const jsEntryPath = path.resolve(dirname, 'src', webEntry[key]).replace(extname, '.tsx')
    if(!fs.existsSync(jsEntryPath)){
        return null
    }
    const htmlEntryPath = name
    // console.log({extname})
    // entry[] 
    return {
      jsEntryKey,
      jsEntryPath,
      htmlEntryPath,
    }
  }).filter(Boolean)
  console.log({ entryArray })
  return entryArray
}
const entryArray = dealEntry(webEntry)
const defineMap = {
  // NODE_ENV: process.env.NODE_ENV,
  // publicPath: publicPath,
};
const templateParameters = {
}
const mockEnv ={};
injectEnv.forEach(key => {

  let value;
  if (Array.isArray(key)) {
    if (process.env[key[0]]) {
      value = process.env[key[0]]
    } else {
      value = key[1];
      mockEnv[key[0]] = value
    }
    key = key[0];
  } else {

    value = process.env[key] || '';
  }

  defineMap[key] = value
})
injectHtml.forEach(key => {

  let value;
  if (Array.isArray(key)) {
    if (process.env[key[0]]) {
      value = process.env[key[0]]
    } else {
      value = key[1];
    }
    key = key[0];
  } else {

    value = process.env[key] ||mockEnv[key]|| '';
  }

  templateParameters[key] = value
})
const plugins = [];
// console.log('process.env==', process.env, injectHtml, injectEnv)

  entryArray.forEach(itme => {
    entry[itme.jsEntryKey] = itme.jsEntryPath;
    plugins.push(new HtmlWebpackPlugin({
      filename: path.resolve(dirname, `./dist/${itme.htmlEntryPath}`),
      template: path.resolve(dirname, `./public/${itme.htmlEntryPath}`),
      templateParameters: {
        entryPath: `${templateParameters.publicPath}/${itme.jsEntryKey}.js?v=${Number(new Date())}`,
        ...templateParameters
      },
      inject: false,
    }),
    )
  })
console.log({ entry })

if(filterEntry){
   let _entry ={};
   Object.keys(entry).forEach(key=>{
       if(filterEntry(key,entry[key])){
        _entry[key] = entry[key]
       }
   })
   entry = _entry;
}
console.log({ entry })

module.exports = {
  entry,
  output: {
    filename: '[name].js',
    path: path.resolve(dirname, './dist'),
    // clean: true,
    publicPath: '',
    libraryTarget: 'umd',
  },
  externals: {
    react: 'react',
    'react-dom': 'react-dom',
    'react-dom/server': 'react-dom/server',
    moment: 'moment',
    antd: 'antd',
    '@ant-design/plots':'@ant-design/plots',
    lodash: 'lodash',
    axios: 'axios',
  },
  stats: 'errors-warnings',
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    alias: {
      '@': path.resolve(dirname, './src'),
    },
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: {
          loader: "swc-loader",
          options: {
            jsc: {
              transform: { react: { runtime: 'automatic' } },

              parser: {
                syntax: "typescript"
              }
            }
          }
        }
        // options: {
        //   transpileOnly: true,
        //   getCustomTransformers: (program) => {

        //     // const transformer = tsTransformPaths(program);
        //     return {
        //       before: [before()]
        //     }
        //   }
        // },
      },
      {
        test: /\.less$/,
        // exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
          },
          {
            loader: "postcss-loader",
          },
          {
            loader: 'less-loader',
            options: {
              lessOptions: { javascriptEnabled: true },
            },
          },
        ],
      },
      {
        test: /\.(jpg|png|gif|bmp|jpeg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              outputPath: '/static/resource/img/',
              publicPath: (defineMap.publicPath + '/static') + '/resource/img/',
              limit: 8192,
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.svg$/,
        exclude: /node_modules/,
        loader: '@svgr/webpack',
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': JSON.stringify(defineMap),
    }),
    ...plugins
  ],
  optimization: {
    usedExports: false,
  },
};
